﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace PingRT
{
    class IconBuild
    {
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = CharSet.Auto)]
        extern static bool DestroyIcon(IntPtr handle);

        public static Icon getIcon(string text)
        {
            Bitmap bitmap = new Bitmap(96, 96);
            //IntPtr ptr = bitmap.GetHicon();
            //Icon icon = Icon.FromHandle(ptr);
            //Icon icon = Icon.FromHandle(bitmap.GetHicon());

            //Meiryo UI font
            System.Drawing.Font drawFont = new System.Drawing.Font("Verdana", 46);
            //System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
            System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White);
            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
            
            /*
            //创建截图路径
            GraphicsPath gpath = new GraphicsPath();
            gpath.AddEllipse(0, 0, 32, 32);//圆形
            graphics.SetClip(gpath);
             * 
             * */

            
            //居中 
            SizeF length = graphics.MeasureString(text, drawFont);
            int width = Convert.ToInt16(length.Width);
            int alginWidth = (96 - width) / 2;
            int height = Convert.ToInt16(length.Height);
            int alginHeight = (96 - height) / 2;

            graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;
            //graphics.DrawIcon(icon, 0, 0);
            graphics.Clear(Color.Empty);
            
            graphics.DrawString(text, drawFont, drawBrush, alginWidth, alginHeight);

            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.CompositingQuality = CompositingQuality.HighQuality;

            graphics.Flush();
            //Icon createdIcon = Icon.FromHandle(bitmap.GetHicon());
            //drawFont.Dispose();
            //drawBrush.Dispose();
            //graphics.Dispose();
            //bitmap.Dispose();
            //icon.Dispose();
            //DestroyIcon(icon.Handle);
            //DestroyIcon(createdIcon.Handle);
            //Utils.ReleaseMemory(true);
            return Icon.FromHandle(bitmap.GetHicon());
        }
    }
}
